/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.semantic;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Class representing a hierarchical structure to the ontology.
 * @author grupo JFTS
 *
 */
public class JFTSHierarchy {
	private JFTSHierarchyNode root = null;
	
	public JFTSHierarchy(JFTSHierarchyNode root){
		this.root = root;
	}
	
	public JFTSHierarchyNode getRoot(){
		return root;
	}
	
	/**
	 * Print the hierarchical structure on PrintStream.
	 * @param out
	 */
	public void printHierarchy(PrintStream out){
		_printHierarchy(out, root, new ArrayList<JFTSHierarchyNode>(), 0, false);
	}
	
	/**
	 * Print the hierarchical structure on PrintStream.<br>
	 * Show the amount of instances per class.
	 * @param out
	 * @param printAmount
	 */
	public void printHierarchy(PrintStream out, boolean printAmount){
		_printHierarchy(out, root, new ArrayList<JFTSHierarchyNode>(), 0, printAmount);
	}	
	
	private void _printHierarchy(PrintStream out, JFTSHierarchyNode node, List<JFTSHierarchyNode> occurs, int level, boolean printAmount){
		_printNode(out, node, level, printAmount);
        out.println();
        
        if (!occurs.contains(node)){
			for (Iterator<JFTSHierarchyNode> it = node.listSubNodes();  it.hasNext(); ) {
				JFTSHierarchyNode nodeAux = it.next();
				occurs.add(node);
				_printHierarchy(out, nodeAux, occurs, level + 1, printAmount);
				occurs.remove(node);
			}
        }
	}	
	
	private void _printNode(PrintStream out, JFTSHierarchyNode node, int level, boolean printAmount){
		_indent(out, level);
		if (printAmount){
			out.print(node.getId() + " [" + node.getAmount() + "]");
		}
		else{
			out.print(node.getId());
		}
	}
	
	
    private void _indent(PrintStream out, int level) {
        for (int i = 0;  i < level; i++) {
            out.print("  ");
        }
    }
}
